#include <iostream>
#include <sys/types.h>
#include <sys/socket.h>
#include <netinet/in.h>
#include <arpa/inet.h>
#include <string>
#include <strings.h>
#include <cstdio>
#include <errno.h>
#include <unistd.h>
using namespace std;

void Usage(std::string proc)
{
    std::cout << "\n\rUsage: " << proc << " serverip serverport\n"
              << std::endl;
}

int main(int argc,char*argv[])//服务器的ip和端口是暴露出来的，所以我们已知。
{
    if(argc!=3) //参数个数不对
    {
        Usage(argv[0]);
        exit(0);
    }

    string serverip=argv[1];
    uint16_t serverport=stoi(argv[2]);

    struct sockaddr_in server;
    bzero(&server,sizeof(server));

    server.sin_family=AF_INET;
    server.sin_port=htons(serverport);
    server.sin_addr.s_addr=inet_addr(serverip.c_str());
    
    socklen_t len=sizeof(server);

    int sockfd=socket(AF_INET,SOCK_DGRAM,0);
    if(sockfd <0)
    {
        cout<<"socker error"<<endl;
        return 1;
    }

    string message;//字符串的话，不用减一
    char buffer[1024];
    while(true)
    {
        cout<<"Please Enter@ ";
        getline(cin,message);

        sendto(sockfd,message.c_str(),message.size(),0,(struct sockaddr*)&server,len);

        struct sockaddr_in temp;
        socklen_t llen=sizeof(temp);

        ssize_t s=recvfrom(sockfd,buffer,1023,0,(struct sockaddr*)&temp,&llen);

        if(s>0)
        {
            buffer[s]=0;
            cout<<"我get message"<<buffer<<endl;
        }
    }

    close(sockfd);
    return 0;
}